/**
 * 七日登录
 */
import {utils} from "../utils/utils";
import {model} from "../web/model/Model";
import {apiUtils} from "../web/api/ApiUtils";
import * as config from "../config/config";
import {wxUtils} from "../wx/wxUtils";

let sevenDayConfig = config.configGetter('sevenday', 'time');

enum SevenDayState {unsign, signed};

const {ccclass, property} = cc._decorator;

class SevenDayItem extends cc.Component {
  private _frame: cc.Node = null;
  private _signed: cc.Node = null;
  private _elapsed: cc.Node = null;

  onLoad() {
    this._frame = this.node.getChildByName('frame');
    this._signed = this._frame.getChildByName('signed');
    this._elapsed = this._frame.getChildByName('elapsed');
  }

  init(curDay, dayIndex, state) {
    if (state === SevenDayState.signed) {
      this.setSigned();
    } else {
      (curDay > dayIndex) ? this.setMissed() : this.setDefault();
      (curDay === dayIndex) && this.setCanGet();
    }
    let rewardID = sevenDayConfig(dayIndex, 'reward');
    let itemID = config.getReward(rewardID, 'itemid');
    // 描述
    let itemName: string = config.getItem(itemID, 'name');
    let desc: cc.RichText = this.node.getChildByName('reward').getComponent(cc.RichText);
    desc.fontSize = 18;
    desc.string = `${itemName}x${config.getReward(rewardID, 'number')}`;

    // 图标
    let icon: cc.Sprite = this._frame.getChildByName('icon').getComponent(cc.Sprite);
    cc.loader.loadRes(`icon/${config.getItem(itemID, 'iconid')}`, cc.SpriteFrame, function (err, frame) {
      err ? cc.log(err) : (icon.spriteFrame = frame);
    });
    // 碎片
    if (config.ResType.skinPiece === config.getItem(itemID, 'type')) {

      cc.loader.loadRes(`icon/piece`, cc.SpriteFrame, function (err, frame) {
        if (err) {
        } else {
          let piece = new cc.Node('piece');
          piece.parent = icon.node;
          piece.addComponent(cc.Sprite).spriteFrame = frame;
          piece.x = (icon.node.width - piece.width) / 2;
          piece.y = (icon.node.height - piece.height) / 2;
        }
      });
    }
  }

  setDefault() {
    // 未领取，未错过
    this._signed.active = false;
    this._elapsed.active = false;
  }

  setCanGet() {
    let shake = () => {
      let onceTime = 0.05;
      let seq = cc.sequence(
        cc.rotateTo(onceTime, -10),
        cc.rotateTo(onceTime * 2, 10),
        cc.rotateTo(onceTime * 2, -10),
        cc.rotateTo(onceTime * 2, 10),
        cc.rotateTo(onceTime, 0),
        cc.delayTime(Math.random() * 2 + 1),
        cc.callFunc(shake)
      );
      this._frame.runAction(seq);
    };
    shake();
    this._frame.on(cc.Node.EventType.TOUCH_END, this._requestSign, this);
  }

  private _requestSign() {
    model.commonResult.once('0', () => {
      model.user.sevenLoginSignOK();
      this._signSuccess();
    }, this);
    apiUtils.signSevenLogin();
  }

  private _signSuccess() {
    this._frame.stopAllActions();
    this._frame.rotation = 0;
    this._frame.off(cc.Node.EventType.TOUCH_END, this._requestSign, this);
    this.setSigned();
  }

  setMissed() {
    // 错过，未签到
    this._signed.active = false;
    this._elapsed.active = true;
  }

  setSigned() {
    // 已领取
    this._signed.active = true;
    this._elapsed.active = true;
  }
}

@ccclass
export default class SevenDay extends cc.Component {

  private _items: SevenDayItem[] = [];

  start() {
    let bg = this.node.getChildByName('bg');
    utils.dialogPopup(this.node, bg);
    // 底部显示的最终奖励
    let name7th = bg.getChildByName('img_line2').getChildByName('name7th');
    let itemID = config.getReward(sevenDayConfig(7, 'reward'), 'itemid');
    name7th.getComponent(cc.Label).string = config.getItem(itemID, 'name');

    let curDay = model.user.sevenLoginInfo.loginDays;
    let states = model.user.sevenLoginInfo.states;
    for (let ix = 0; ix < states.length; ix++) {
      let dayIx = ix + 1;
      let node = bg.getChildByName(`day${dayIx}`);
      node.addComponent(SevenDayItem).init(curDay, dayIx, states[ix]);
    }

    let block = this.node.getChildByName('block');  // 屏蔽点击的全屏黑色半透背景
    let content = bg.getChildByName('content');  // 点击content外部关闭，bg的空白像素范围有点大

    block.on(cc.Node.EventType.TOUCH_END, (event: cc.Event.EventTouch) => {
      let p = content.convertTouchToNodeSpace(event.touch);
      if (p.x < 0 || p.x > content.width || p.y < 0 || p.y > content.height) {
        this.close();
      }
    }, this);
  }

  close() {
    utils.dialogClose(this.node, this.node.getChildByName('bg'));
    wxUtils.showMenuAd()
  }

}
